<?php

/**
 * 媒资导入接口
 */
include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'db.class.php';
include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'curl.class.php';
include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/nn_logic/nl_common.func.php';
include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/nn_logic/video/vod_media.class.php';
include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/nn_logic/nns_media_asset_import_log/nns_media_asset_import_log.class.php';

class import_assets_class extends db {

        public $log = "";
        public $vod_id;
        public static $dc;
        public $re_code = array();

        function import_assets() {
                $obj = @simplexml_load_string($_POST['assets_content']);
                $asset_info = json_decode(json_encode($obj), true);	
                
               			
//写日志
              	if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                        $this->write_logs($asset_info, "注入媒资开始验证，媒资信息为：");
                
  
              	}             
                
//对参数进行检查
                $check = $this->import_assets_check_params($asset_info);
//如果有需要处理的ftp图片处理失败,直接返回，不再往下走
                if ($check === false) {
//写错误日志
                        $this->error_logs($asset_info, "以上媒资注入信息验证失败");
                        return $this->re_code;
                } else {
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs("", "以上媒资注入信息验证成功开始导入");
                        }
                }
//1、组装父类db可以插入的参数
                $params_db = array(
                    "assets_category" => $asset_info["@attributes"]["assets_category"],
                    "video_type" => $asset_info["@attributes"]["video_type"],
                    "name" => $asset_info["@attributes"]["name"],
                    "sreach_key" => $asset_info["@attributes"]["sreach_key"],
                    "view_type" => $asset_info["@attributes"]["view_type"],
                    "director" => $asset_info["@attributes"]["director"],
                    "player" => $asset_info["@attributes"]["player"],
                    "tag" => $asset_info["@attributes"]["tag"],
                    "region" => $asset_info["@attributes"]["region"],
                    "release_time" => $asset_info["@attributes"]["release_time"],
                    "totalnum" => $asset_info["@attributes"]["totalnum"],
                    "intro" => $asset_info["@attributes"]["intro"],
                    "producer" => $asset_info["@attributes"]["producer"],
                    "adaptor" => $asset_info["@attributes"]["adaptor"],
                    "point" => 0,
                    "play_role" => $asset_info["@attributes"]["play_role"],
                    "subordinate_name" => $asset_info["@attributes"]["subordinate_name"],
                    "english_name" => $asset_info["@attributes"]["english_name"],
                    "language" => $asset_info["@attributes"]["language"],
                    "caption_language" => $asset_info["@attributes"]["caption_language"],
                    "view_len" => "0",
                    "copyright_range" => $asset_info["@attributes"]["copyright_range"],
                    "copyright" => $asset_info["@attributes"]["copyright"],
                );
//调用基础函数插入数据库
                $video_id = $this->update_asset($asset_info["@attributes"]["assets_id"], $params_db);
                $this->vod_id = $video_id;
				//var_dump($video_id);die;
				
//如果注入失败
                if ($video_id === false) {
//写错误日志
                        $this->error_logs($params_db, "影片注入基础函数插入影片信息执行失败");
                        $this->re_code = array("ret" => 9, "reason" => "影片注入基础函数插入影片信息执行失败", "id" => $video_id);
                        return $this->re_code;
                } else {
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs("", "影片注入基础信息导入成功返回媒资id为：{$video_id}");
                        }
                }
//组装扩展数据
                $diff_vod_arr_ex = array(
                    "svc_item_id" => $asset_info["@attributes"]["svc_item_id"],
                    "national" => $asset_info["@attributes"]["national"],
                    "initials" => $asset_info["@attributes"]["initials"],
                    "month_clicks" => $asset_info["@attributes"]["month_clicks"],
                    "week_clicks" => $asset_info["@attributes"]["week_clicks"],
                );
//返回cms影片id
                $insert_data_re = self::insert_vod_data_ex($asset_info["@attributes"]["assets_id"], $diff_vod_arr_ex);
                if ($insert_data_re === false) {
//写错误日志
                        $this->error_logs($diff_vod_arr_ex, "扩展数据导入失败");
                        $this->re_code = array("ret" => 9, "reason" => "影片注入扩展数据导入失败", "id" => $video_id);
                        return $this->re_code;
                } else {
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs($diff_vod_arr_ex, "扩展数据导入成功");
                        }
                }
//组装剩余是需要插入vod表的数据
                $diff_vod_arr = array(
                    "image0" => $asset_info["@attributes"]["bigpic"],
                    "image2" => $asset_info["@attributes"]["smallpic"],
                    "play_count" => $asset_info["@attributes"]["total_clicks"], //点击数
                    "tag" => "26,"//yxt这里写死了，以后如果mgtv要扩展需要修改接口文档
                );
                $insert_data_re = self::insert_vod_data($this->vod_id, $diff_vod_arr);
                if ($insert_data_re === false) {
//写错误日志
                        $this->error_logs($diff_vod_arr, "vod基础函数插入的剩余数据导入失败");
                        $this->re_code = array("ret" => 9, "reason" => "基础函数插入影片信息执行失败", "id" => $video_id);
                        return $this->re_code;
                } else {
//写日志
                        $this->write_logs($diff_vod_arr, "vod基础函数插入的剩余数据导入成功");
                }
                $this->re_code = array("ret" => 0, "reason" => "插入成功", "id" => $video_id);
//2、插入分片和片源
                if (is_array($asset_info["indexes"]["index"])) {
//如果是一个分片
                        if (array_key_exists("@attributes", $asset_info["indexes"]["index"])) {
                                $re = $this->insert_index_data($asset_info["@attributes"]["assets_id"], $asset_info["indexes"]["index"]["@attributes"], $asset_info["indexes"]["index"]["media"]);
                        } else {//如果有多个分片
                                foreach ($asset_info["indexes"]["index"] as $key_clip => $val_clip) {
                                        $re = $this->insert_index_data($asset_info["@attributes"]["assets_id"], $val_clip["@attributes"], $val_clip["media"]);
                                        if ($re === false) {
                                                break;
                                        }
                                }
                        }
                }
            	include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/mgtv/fjyd/models/clip_task_model.php';
            	clip_task_model::add_task_by_vod_id( $video_id);
                return $this->re_code;
        }

        /**
         * 将基础函数没有插入的数据入扩展库
         * @param string $video_id:影片id
         * @param array $params
         */
        private function insert_vod_data_ex($video_id, $params = array()) {
                if (empty($params) || empty($video_id)) {
                        return null;
                }
                $val = "";
                foreach ($params as $key => $v) {
                        if (!empty($v)) {
                                $val.="('{$video_id}','{$key}','{$v}'),";
                        }
                }
                $val = trim($val, ',');
                $sql = "replace into nns_vod_ex values{$val}";
                return nl_execute_by_db($sql, $this->dc->db());
        }

        /**
         * 将基础函数没有插入的数据入vod表
         * @param string $video_id:影片id
         * @param array $params
         */
        private function insert_vod_data($video_id, $params = array()) {
                if (empty($params) || empty($video_id)) {
                        return null;
                }
                $set = "";
                foreach ($params as $key => $v) {
                        $set.="nns_{$key}='{$v}',";
                }
                $set = trim($set, ',');
               //$sql = "update nns_assists_item as a,nns_vod as v set a.nns_video_img2='{$params['image2']}',a.nns_play_count='{$params['play_count']}' where a.nns_video_id=v.nns_id and (v.nns_id='{$video_id}' or v.nns_asset_import_id='{$video_id}')";
               // nl_execute_by_db($sql, $this->dc->db());
                $sql = "update nns_vod set {$set} where nns_id='{$video_id}' OR nns_asset_import_id='{$video_id}'";
                return nl_execute_by_db($sql, $this->dc->db());
        }

        /**
         * 注入分片
         * @param string $vod_id:注入影片id
         * @param array $params_index:分片信息
         * @param array $params_media:片源信息
         * @return bool：注入是否成功，有可能是分片注入或者是片源注入的情况
         */
        private function insert_index_data($vod_id, $params_index = array(), $params_media = array()) {
                $params_clip = array(
                    "index" => $params_index["index"],
                    "time_len" => $params_index["time_len"],
                    "name" => $params_index["name"],
                    "summary" => $params_index["summary"],
                    "director" => $params_index["director"],
                    "player" => $params_index["player"],
                );
//调用基础函数插入分片信息
                $insert_clip = $this->update_clip($vod_id, $params_index["clip_id"], $params_clip);
                if ($insert_clip === false) {
//写错误日志
                        $this->error_logs($params_index, "影片id为{$vod_id}的分片id为{$params_clip["index"]}的分片注入失败，请重新注入影片");
                        $this->re_code = array("ret" => 9, "reason" => "影片id为{$vod_id}的分片id为{$params_clip["index"]}的分片注入失败，请重新注入影片", "id" => $this->vod_id);
                        return false;
                } else {
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs($params_clip, "影片id为{$vod_id}的分片id为{$params_clip["index"]}的分片注入成功");
                        }
                }
//组织剩余的数据
                $diff_index_arr = array(
                    "image" => $params_index["pic"],
                    "play_count" => $params_index["total_clicks"],
                    "create_time" => $params_index["update_time"],
                );
                $sql_update_index = "update nns_vod_index set nns_create_time='{$diff_index_arr['create_time']}',nns_image='{$diff_index_arr["image"]}',nns_play_count='{$diff_index_arr['play_count']}' where nns_id='{$insert_clip}'";
                $rr = nl_execute_by_db($sql_update_index, $this->dc->db());
                if ($rr === false) {
//写错误日志
                        $this->error_logs($diff_index_arr, "影片id为{$vod_id}的分片id为{$params_clip["index"]}的分片剩余数据注入失败，请重新注入影片");
                        $this->re_code = array("ret" => 9, "reason" => "影片id为{$vod_id}的分片id为{$params_clip["index"]}的分片剩余数据注入失败，请重新注入影片", "id" => $this->vod_id);
                        return false;
                } else {
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs($diff_index_arr, "影片id为{$vod_id}的分片id为{$params_clip["index"]}的分片剩余数据注入成功");
                        }
                }
//插入片源信息
//如果只有一个片源
                $if_ok_import_file = true;
                if (!empty($params_media)) {
                        if (array_key_exists("@attributes", $params_media)) {
                                $if_ok_import_file = $this->insert_media_data($vod_id, $params_index["clip_id"], $params_media["@attributes"], $params_index["time_len"]);
                        } else {//如果只有多个片源
                                foreach ($params_media as $key_media => $val_media) {
                                        $if_ok_import_file = $this->insert_media_data($vod_id, $params_index["clip_id"], $val_media["@attributes"], $params_index["time_len"]);
                                        if ($if_ok_import_file === false) {
                                                break;
                                        }
                                }
                        }
                }
                return $if_ok_import_file;
        }

        /**
         * 备注：芒果的没有片源时间，这里直接使用分片的时间
         * @param string $asset_import_id:影片注入id
         * @param string $clip_import_id :分片注入id
         * @param array $params_media    :片源信息
         * @param int $index_time_len
         * @return bool,片源是否注入成功
         */
        private function insert_media_data($asset_import_id, $clip_import_id, $params_media = array(), $index_time_len = 0) {
//		echo "<pre>";print_r($params_media);

				if ($params_media["file_3d"]){
					if ($params_media["file_3d_type"]==0){
						$file_dimensions=nl_vod_media::DIMENSIONS_3D_LEFT_RIGHT;
					}elseif ($params_media["file_3d_type"]==1){
						$file_dimensions=nl_vod_media::DIMENSIONS_3D_UP_DOWN;
					}
                	
                }else{
                	$file_dimensions='0';
                }
                $params_file = array(
                    "file_name" => "", //分片名称
                    "file_type" => $params_media["file_type"],
                    "file_path" => $params_media["file_path"],
                    "file_definition" => $params_media["file_definition"],
                    "file_bit_rate" => $params_media["file_bit_rate"],
                    "file_desc" => $params_media["file_desc"],
                    "file_time_len" => $index_time_len, //这里直接使用分片的时间
                    "file_dimensions"=>$file_dimensions
                );
                $insert_file = $this->update_file($asset_import_id, $clip_import_id, $params_media['file_id'], $params_file);
                if ($insert_file === false) {
//写错误日志
                        $this->error_logs($params_file, "影片id为{$asset_import_id}的分片id为{$clip_import_id}的分片片源注入失败，分片数据为");
                        $this->re_code = array("ret" => 9, "reason" => "影片id为{$asset_import_id}的分片id为{$clip_import_id}的分片片源注入失败，请重新注入影片", "id" => $this->vod_id);
                        return false;
                } else {
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs($params_file, "影片id为{$asset_import_id}的分片id为{$clip_import_id}的分片片源注入成功");
                        }
                }
                return $insert_file;
        }

        /**
         * 将导入的xml转化数组之后传入进来，对参数进行检测
         * @param array $params
         * @return bool 是否验证成功
         */
        private function import_assets_check_params($params = array()) {
//对影片的参数进行 检查
                //
                if (empty($params["@attributes"]["assets_id"]) || empty($params["@attributes"]["name"])) {
                        $this->re_code = array("ret" => 1, "reason" => "媒资id或者媒资名称为空", "id" => $this->vod_id);
                        return false;
                }

//判断是否需要对图片进行ftp处理，如果之后添加图片，则在这里添加代码
                $log = array();
                $check_img_vod1 = $this->img_handel($params["@attributes"]['smallpic']);

                $log['nns_import_video_id'] = $params["@attributes"]['assets_id'];
                $log['nns_video_name'] = $params["@attributes"]['name'];
                $log['nns_error_code'] = '1001000';
                $log['nns_import_type'] = $params["@attributes"]['video_type'];

                if ($check_img_vod1 === 0 || $check_img_vod1 === false) {
                        $log['nns_error_desc'] = "smallpic={$params["@attributes"]['smallpic']}";
                        nl_media_asset_import_log::add_log($this->dc, $log);
                }
                if (isset($params["@attributes"]['bigpic']) && !empty($params["@attributes"]['bigpic'])) {
                        $check_img_vod2 = $this->img_handel($params["@attributes"]['bigpic']);
                        if ($check_img_vod2 === 0 || $check_img_vod2 === false) {
                                $log['nns_error_desc'] = "bigpic={$params["@attributes"]['bigpic']}";
                                nl_media_asset_import_log::add_log($this->dc, $log);
                        }
                }
                if ($check_img_vod1 === false || $check_img_vod1 === 0) {
                        return false;
                }

                if (is_array($params["indexes"]) && array_key_exists("index", $params["indexes"])) {//如果有分片信息
//对分片进行检查
                        if (array_key_exists("@attributes", $params["indexes"]["index"])) {//如果只有一个分片
                                if (empty($params["indexes"]["index"]["@attributes"]["clip_id"]) || (empty($params["indexes"]["index"]["@attributes"]["index"]) && $params["indexes"]["index"]["@attributes"]["index"] != "0")) {
                                        $this->re_code = array("ret" => 1, "reason" => "分片0个的参数clip_id或者index为空", "id" => $this->vod_id);
                                        return false;
                                }
//判断是否需要对图片进行ftp处理
                                $check_img_index = $this->img_handel($params["indexes"]["index"]["@attributes"]["pic"]);
                                if ($check_img_index === 0 || $check_img_index === false) {
                                        $log['nns_error_desc'] = "pic={$params["indexes"]["index"]["@attributes"]["pic"]},index=0";
                                        nl_media_asset_import_log::add_log($this->dc, $log);
                                }
                                if ($check_img_index === false || $check_img_index === 0) {
                                        return $check_img_index;
                                }
//对片源进行检查
                                if (array_key_exists("media", $params["indexes"]["index"])) {
                                        if (array_key_exists("@attributes", $params["indexes"]["index"]["media"])) {//如果只有一个片源
                                                if (empty($params["indexes"]["index"]["media"]["@attributes"]["file_id"]) || empty($params["indexes"]["index"]["media"]["@attributes"]["file_type"])) {
                                                        $this->re_code = array("ret" => 1, "reason" => "第0个分片的0个片源的参数clip_id或者index为空", "id" => $this->vod_id);
                                                        return false;
                                                }
                                        } else {//如果有多个片源
                                                foreach ($params["indexes"]["index"]["media"] as $k2 => $file_item) {
                                                        if (empty($file_item["file_id"]) || empty($file_item["file_type"])) {
                                                                $this->re_code = array("ret" => 1, "reason" => "第0个分片的{$k2}个片源的参数clip_id或者index为空", "id" => $this->vod_id);
                                                                return false;
                                                        }
                                                }
                                        }
                                }
                        } else {//如果有多个分片
                                foreach ($params["indexes"]["index"] as $k => $clip_item) {
                                        if (empty($clip_item["@attributes"]["clip_id"]) || (empty($clip_item["@attributes"]["index"]) && $clip_item["@attributes"]["index"] != "0")) {
                                                $this->re_code = array("ret" => 1, "reason" => "第{$k}个分片参数clip_id或者index为空", "id" => $this->vod_id);
                                                return false;
                                        }
//判断是否需要对图片进行ftp处理


                                        $check_img_index = $this->img_handel($clip_item["@attributes"]["pic"]);

                                        if ($check_img_index === 0  || $check_img_index === false) {
                                                $log['nns_error_desc'] = "pic={$clip_item["@attributes"]["pic"]},index=$k";
                                                nl_media_asset_import_log::add_log($this->dc, $log);
                                        }
//对片源进行检查
                                        if (array_key_exists("media", $params["indexes"]["index"])) {
                                                if (array_key_exists("@attributes", $params["indexes"]["index"]["media"])) {//如果只有一个片源
                                                        if (empty($params["indexes"]["index"]["media"]["@attributes"]["file_id"]) || empty($params["indexes"]["index"]["media"]["@attributes"]["file_type"])) {
                                                                $this->re_code = array("ret" => 1, "reason" => "第{$k}个分片的0个片源的参数clip_id或者index为空", "id" => $this->vod_id);
                                                                return false;
                                                        }
                                                } else {//如果有多个片源
                                                        foreach ($params["indexes"]["index"]["media"] as $k2 => $file_item) {
                                                                if (empty($file_item["file_id"]) || empty($file_item["file_type"])) {
                                                                        $this->re_code = array("ret" => 1, "reason" => "第{$k}个分片的0个片源的参数clip_id或者index为空", "id" => $this->vod_id);
                                                                        return false;
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                }
                return true;
        }

        /**
         * 影片信息修改
         */
        public function modify_video() {
//判断是否为点播（目前只支持点播）
                if ($_POST["assets_video_type"] != 0) {
                        $this->re_code = array("ret" => 1, "reason" => "请传递点播类型的影片");
                        return $this->re_code;
                }
//判断是否传递了影片id
                if (empty($_POST["assets_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容id为空");
                        return $this->re_code;
                }
//将xml解析为数组，检查参数是否正确
                $obj = simplexml_load_string($_POST['assets_video_info']);
                $asset_info = json_decode(json_encode($obj), true);
//对参数进行检查
                $check = $this->modify_video_check_params($asset_info);
//如果图片处理失败
                if ($check === false) {
                        return $this->re_code;
                }
                if ($check["if_ok"] !== true) {
                        $this->re_code = array("ret" => 1, "reason" => $check["reason"]);
                        return $this->re_code;
                }
//获取影片id
                $asset_id = $_POST["assets_id"];
                $params_db = array(
                    "assets_category" => $asset_info["@attributes"]["assets_category"],
                    "video_type" => $asset_info["@attributes"]["video_type"],
                    "name" => $asset_info["@attributes"]["name"],
                    "sreach_key" => $asset_info["@attributes"]["sreach_key"],
                    "view_type" => $asset_info["@attributes"]["view_type"],
                    "director" => $asset_info["@attributes"]["director"],
                    "player" => $asset_info["@attributes"]["player"],
                    "tag" => $asset_info["@attributes"]["tag"],
                    "region" => $asset_info["@attributes"]["region"],
                    "release_time" => $asset_info["@attributes"]["release_time"],
                    "totalnum" => $asset_info["@attributes"]["totalnum"],
                    "intro" => $asset_info["@attributes"]["intro"],
                    "producer" => $asset_info["@attributes"]["producer"],
                    "adaptor" => $asset_info["@attributes"]["adaptor"],
                    "point" => 0,
                    "play_role" => $asset_info["@attributes"]["play_role"],
                    "subordinate_name" => $asset_info["@attributes"]["subordinate_name"],
                    "english_name" => $asset_info["@attributes"]["english_name"],
                    "language" => $asset_info["@attributes"]["language"],
                    "caption_language" => $asset_info["@attributes"]["caption_language"],
                    "view_len" => "0",
                    "copyright_range" => $asset_info["@attributes"]["copyright_range"],
                    "copyright" => $asset_info["@attributes"]["copyright"],
                );
//调用基层函数修改
                $vod_res = $this->update_asset($asset_id, $params_db);
                if ($vod_res === false) {
                        $this->re_code = array("ret" => 9, "reason" => '服务器内部错误');
                } else {
                        $this->re_code = array("ret" => 0, "reason" => '修改成功');
                }
//调用自定义函数修改
                $diff_vod_arr = array(
                    "image0" => $asset_info["@attributes"]["bigpic"], //大海报
                    "image2" => $asset_info["@attributes"]["smallpic"], //小海报
                    "play_count" => $asset_info["@attributes"]["total_clicks"], //点击数
                    "tag" => "26,"//yxt这里写死了，以后如果mgtv要扩展需要修改接口文档
                );
                $insert_data_re = self::insert_vod_data($asset_info["@attributes"]["assets_id"], $diff_vod_arr);
//调用自定义函数扩展信息修改
                $diff_vod_arr_ex = array(
                    "svc_item_id" => $asset_info["@attributes"]["svc_item_id"],
                    "national" => $asset_info["@attributes"]["national"],
                    "initials" => $asset_info["@attributes"]["initials"],
                    "month_clicks" => $asset_info["@attributes"]["month_clicks"],
                    "week_clicks" => $asset_info["@attributes"]["week_clicks"],
                );
                $insert_data_re = self::insert_vod_data_ex($asset_info["@attributes"]["assets_id"], $diff_vod_arr_ex);
                return $this->re_code;
        }

        /**
         * 影片参数基础
         * @param $params:影片参数数组
         * @return array $re_arr=("if_ok"=>bool,"reason"=>"错误描述")
         */
        public function modify_video_check_params($params = array()) {

                $log = array();
                $check_img_vod1 = $this->img_handel($params["@attributes"]['smallpic']);

                $log['nns_import_video_id'] = $params["@attributes"]['assets_id'];
                $log['nns_video_name'] = $params["@attributes"]['name'];
                $log['nns_error_code'] = '1001000';
                $log['nns_import_type'] = $params["@attributes"]['video_type'];

                if ($check_img_vod1 === 0 || $check_img_vod1 === false) {
                        $log['nns_error_desc'] = "smallpic={$params["@attributes"]['smallpic']}";
                        nl_media_asset_import_log::add_log($this->dc, $log);
                }
                if (isset($params["@attributes"]['bigpic']) && !empty($params["@attributes"]['bigpic'])) {
                        $check_img_vod2 = $this->img_handel($params["@attributes"]['bigpic']);
                        if ($check_img_vod2 === 0 || $check_img_vod2 === false) {
                                $log['nns_error_desc'] = "bigpic={$params["@attributes"]['bigpic']}";
                                nl_media_asset_import_log::add_log($this->dc, $log);
                        }
                }
                if ($check_img_vod1 === false || $check_img_vod1 === 0) {
                        return false;
                }
                if (is_array("$params") && array_key_exists("@attributes", $params)) {
                        if (empty($params["@attributes"]["assets_id"])) {
                                return array("if_ok" => false, "reason" => "来源媒资id为空");
                        }
                }
                return array("if_ok" => true, "reason" => "参数正确");
        }

        /**
         * 媒资删除
         */
        public function delete_asset() {

//判断参数
                if (empty($_POST["assets_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "没有内容id参数");
                        return $this->re_code;
                }
                if ($_POST["assets_video_type"] != 0) {
                        $this->re_code = array("ret" => 1, "reason" => "请传递点播类型影片");
                        return $this->re_code;
                }
                $res_del = parent::delete_asset(array("id" => $_POST["assets_id"]));
                if ($res_del) {
                        $this->re_code = array("ret" => 0, "reason" => "删除成功");
                        return $this->re_code;
                } elseif ($res_del === false) {
                        $this->re_code = array("ret" => 2, "reason" => "删除失败");
                        return $this->re_code;
                } else {
                        $this->re_code = array("ret" => 2, "reason" => "数据不存在");
                        return $this->re_code;
                }
        }

        /**
         * 分片注入
         */
        public function import_video_clip() {
//判断参数是否传递
                if (empty($_POST['assets_id'])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容id为空");
                        return $this->re_code;
                }
                if (empty($_POST['assets_clip_id'])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容分片id为空");
                        return $this->re_code;
                }
//将xml解析为数组，检查参数是否正确
               
                $obj = simplexml_load_string($_POST['assets_clip_info']);
                $clip_info = json_decode(json_encode($obj), true);
//写日志
                if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                        $this->write_logs($clip_info, "注入分片开始，媒资信息为：");
                
                }
				                
//对参数进行检查，和对图片ftp处理
                $check = $this->import_video_clip_ckeck_params($clip_info);
//如果图片处理失败
                if ($check === false) {
                        $this->write_logs(var_export($this->re_code, true), "图片处理失败");
                        return $this->re_code;
                }
                if ($check["if_ok"] !== true) {
                        $this->re_code = array("ret" => 1, "reason" => $check["reason"]);
                        return $this->re_code;
                }
                
                
                
//组合db需要的数组,yxt:后面2个元素：导演和演员是后来加的
                $params_clip = array(
                    "index" => $clip_info["@attributes"]['index'],
                    "time_len" => $clip_info["@attributes"]["time_len"],
                    "name" => $clip_info["@attributes"]["name"],
                    "summary" => $clip_info["@attributes"]["summary"],
                    "director" => $clip_info["@attributes"]["director"],
                    "player" => $clip_info["@attributes"]["player"],
                );
                $insert_clip = $this->update_clip($_POST['assets_id'], $_POST['assets_clip_id'], $params_clip);
                if (!empty($insert_clip)) {
                        $this->re_code = array("ret" => 0, "reason" => "注入成功");

//			MGTV需要取第一个分片的信息当做影片片长来保存 BY S67 2013-04-30
                        if ($params_clip['index'] == 0) {
                                $this->modify_vod_other_data($_POST['assets_id'], array(
                                    'view_len' => $params_clip['time_len']
                                ));
                        }



//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs(null, "基础信息注入成功");
                        }
//插入剩余的数据
//改动
                        $clip_info['@attributes']['pic'] = $clip_info['@attributes']['pic'];
                        $sql_update_index = "update nns_vod_index set nns_create_time='{$clip_info['@attributes']['release_time']}',nns_modify_time='{$clip_info['@attributes']['update_time']}', nns_image='{$clip_info['@attributes']['pic']}',nns_play_count='{$clip_info['@attributes']['total_clicks']}' where nns_id='{$insert_clip}'";
                        $r = nl_execute_by_db($sql_update_index, $this->dc->db());
                        if ($r !== false) {
//写日志
                                if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                        $this->write_logs($sql_update_index, "扩展信息注入成功");
                                }
                        } else {
//写日志
                                if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                        $this->write_logs($sql_update_index, "扩展信息注入失败");
                                }
                        }
                } elseif ($insert_clip === false) {
                        $this->re_code = array("ret" => 3, "reason" => "注入失败");
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs(null, "基础信息注入失败");
                        }
                }
                return $this->re_code;
        }

        /**
         * 检查分片注入参数是否正确
         * @param array $params
         */
        public function import_video_clip_ckeck_params($params = array()) {                
				$check_img_vod = $this->img_handel($params["@attributes"]['pic']);
                if ($check_img_vod === false) {
                        return $check_img_vod;
                }
                if (is_array("$params") && array_key_exists("@attributes", $params)) {
                        if (empty($params["@attributes"]["assets_id"])) {
                                return array("if_ok" => false, "reason" => "来源媒资id为空");
                        }
                }
                return array("if_ok" => true, "reason" => "参数正确");
        }

        /**
         * 分片修改
         */
        public function modify_video_clip() {
//判断参数是否传递
                if (empty($_POST['assets_id'])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容id为空");
                        return $this->re_code;
                }
                if (empty($_POST['assets_clip_id'])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容分片id为空");
                        return $this->re_code;
                }
//将xml解析为数组，检查参数是否正确
                $obj = simplexml_load_string($_POST['assets_clip_info']);
                $clip_info = json_decode(json_encode($obj), true);
//处理图片
                $check_img_index = $this->img_handel($clip_info["@attributes"]['pic']);
                if ($check_img_index === false) {
                        return $this->re_code;
                }
//组合db需要的数组
                $params_clip = array(
                    "index" => $clip_info["@attributes"]['index'],
                    "time_len" => $clip_info["@attributes"]["time_len"],
                    "name" => $clip_info["@attributes"]["name"],
                    "summary" => $clip_info["@attributes"]["summary"],
                    "director" => $clip_info["@attributes"]["director"],
                    "player" => $clip_info["@attributes"]["player"],
                );
                $insert_clip = $this->update_clip($_POST['assets_id'], $_POST['assets_clip_id'], $params_clip);

//			MGTV需要取第一个分片的信息当做影片片长来保存 BY S67 2013-04-30
                if ($params_clip['index'] == 0) {
                        $this->modify_vod_other_data($_POST['assets_id'], array(
                            'view_len' => $params_clip['time_len']
                        ));
                }

                if ($insert_clip) {
                        $this->re_code = array("ret" => 0, "reason" => "修改成功");
                } elseif ($insert_clip === false) {
                        $this->re_code = array("ret" => 9, "reason" => "服务器内部错误");
                }
                return $this->re_code;
        }

        /**
         * 检查分片修改参数是否正确
         * @param array $params
         */
        public function modify_video_clip_ckeck_params($params = array()) {
                if (is_array("$params") && array_key_exists("@attributes", $params)) {
                        if (empty($params["@attributes"]["assets_id"])) {
                                return array("if_ok" => false, "reason" => "来源媒资id为空");
                        }
                }
                return array("if_ok" => true, "reason" => "参数正确");
        }

        /**
         * 分片删除
         */
        public function delete_video_clip() {
     	
                if (empty($_POST["assets_clip_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容分片id为空");
                        return $this->re_code;
                }
                if (!empty($_POST["assets_video_type"])) {
                        $this->re_code = array("ret" => 1, "reason" => "请传递点播分片");
                        return $this->re_code;
                }
                $re = $this->delete_clip(array("id" => $_POST["assets_clip_id"]));
                if ($re) {
                        $this->re_code = array("ret" => 0, "reason" => "删除成功");
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs($_POST, "分片删除成功");
                        }
                } elseif ($re === false) {
//写错误日志
                        $this->error_logs($_POST, "分片删除失败");
                        $this->re_code = array("ret" => 9, "reason" => "分片删除失败");
                }
                return $this->re_code;
        }

        /**
         * 片源注入
         */
        public function import_video_file() {
 
				
				    	
                if (empty($_POST["assets_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容id为空");
                        return $this->re_code;
                }
                if (!empty($_POST["assets_video_type"])) {
                        $this->re_code = array("ret" => 1, "reason" => "请传递点播片源");
                        return $this->re_code;
                }
                if (empty($_POST["assets_clip_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容分片id为空");
                        return $this->re_code;
                }
                if (empty($_POST["assets_file_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容片源id为空");
                        return $this->re_code;
                }
                $obj = simplexml_load_string($_POST['assets_file_info']);
                $file_info = json_decode(json_encode($obj), true);
                if (empty($file_info["@attributes"]["file_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "来源片源id为空");
                        return $this->re_code;
                }
                if (empty($file_info["@attributes"]["file_type"])) {
                        $this->re_code = array("ret" => 1, "reason" => "片源类型为空");
                        return $this->re_code;
                }

				                
                if ($file_info["@attributes"]["file_3d"]){
					if ($file_info["@attributes"]["file_3d_type"]==0){
						$file_dimensions=nl_vod_media::DIMENSIONS_3D_LEFT_RIGHT;
					}elseif ($file_info["@attributes"]["file_3d_type"]==1){
						$file_dimensions=nl_vod_media::DIMENSIONS_3D_UP_DOWN;
					}
                	
                }else{
                	$file_dimensions='0';
                }
                
                
                $params = array(
                    "file_name" => "",
                    "file_type" => $file_info["@attributes"]["file_type"],
                    "file_path" => $file_info["@attributes"]["file_path"],
                    "file_definition" => $file_info["@attributes"]["file_definition"],
                    "file_bit_rate" => $file_info["@attributes"]["file_bit_rate"],
                    "file_desc" => $file_info["@attributes"]["file_desc"],
                    "file_time_len" => "",
                    "file_core_id" => "",
                    "file_dimensions"=>$file_dimensions
                );
                $re = $this->update_file($_POST["assets_id"], $_POST["assets_clip_id"], $_POST["assets_file_id"], $params);
                if ($re) {
                        $this->re_code = array("ret" => 0, "reason" => "片源注入成功");
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs($_POST, "片源注入成功");
                        }
                } elseif ($re === false) {
//写错误日志
                        $this->error_logs($_POST, "片源注入失败");
                        $this->re_code = array("ret" => 9, "reason" => "片源注入失败");
                }
                return $this->re_code;
        }

        /**
         * 删除片源
         */
        public function delete_video_file() {
                if (empty($_POST["assets_file_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容片源ID为空");
                        return $this->re_code;
                }
                if (!empty($_POST["assets_video_type"])) {
                        $this->re_code = array("ret" => 1, "reason" => "请传递点播片源");
                        return $this->re_code;
                }
                $re = $this->delete_file(array("id" => $_POST["assets_file_id"]));
                if ($re) {
                        $this->re_code = array("ret" => 0, "reason" => "片源删除成功");
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs($_POST, "片源删除成功");
                        }
                } elseif ($re === false) {
//写错误日志
                        $this->error_logs($_POST, "片源删除成功");
                        $this->re_code = array("ret" => 9, "reason" => "片源删除失败");
                }
                return $this->re_code;
        }

        /**
         * 资费定价标签同步
         */
        public function update_svc_item_id() {
                if (empty($_POST["assets_video_type"])) {
                        $_POST["assets_video_type"] = 0;
                }
                if (empty($_POST["assets_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "内容片源ID为空");
                        return $this->re_code;
                }
                if (empty($_POST["svc_item_id"])) {
                        $this->re_code = array("ret" => 1, "reason" => "定价标签为空");
                        return $this->re_code;
                }
                $sql = "update nns_vod_ex set nns_value='{$_POST["svc_item_id"]}' where nns_vod_id='{$_POST["assets_id"]}' and nns_key='svc_item_id'";
                $re = nl_execute_by_db($sql, $this->dc->db());
                if ($re) {
                        $this->re_code = array("ret" => 0, "reason" => "定价标签同步成功");
//写日志
                        if (defined("IMPORT_LOG") && IMPORT_LOG === true) {
                                $this->write_logs($_POST, "定价标签同步成功");
                        }
                } elseif ($re === false) {
//写错误日志
                        $this->error_logs($_POST, "定价标签同步成功");
                        $this->re_code = array("ret" => 9, "reason" => "定价标签同步失败");
                }
                return $this->re_code;
        }

        /**
         * 图片处理，当有需要下载和上传的图片的时候都需要调用这个方法来先把图片处理了
         * 如果图片处理没有成功就不进行后面的操作
         * @param string $img_from_addr://下载的ftp的完整的图片地址,有目录
         * @return bool
         */
        private function img_handel($img_from = "") {
        	if(empty($img_from)) return true;
        	/*
                $check_img = stripos($img_from, '/prev/KsImg/');
                if ($check_img === false) {//如果不需要处理
                        return true;
                }
                */
//载入全局的芒果tv的ftp配置数据,是一个二维数组
                global $g_ftp_conf;
//加载np_ftp
                //include_once NPDIR . '/np_ftp.php';
//实例化np_ftp类
//                $ftp_to1 = new nns_ftp($g_ftp_conf['ftp_to1']["address"], $g_ftp_conf['ftp_to1']["user"], $g_ftp_conf['ftp_to1']["password"], $g_ftp_conf['ftp_to1']["port"]);
//                $ftp_to2 = new nns_ftp($g_ftp_conf['ftp_to2']["address"], $g_ftp_conf['ftp_to2']["user"], $g_ftp_conf['ftp_to2']["password"], $g_ftp_conf['ftp_to2']["port"]);
//                if (!$ftp_to1->connect()) {
//                        $this->re_code = array("ret" => 3, "reason" => "上传ftp连接失败,地址:{$g_ftp_conf['ftp_to1']["address"]},用户名:{$g_ftp_conf['ftp_to1']["user"]},密码:{$g_ftp_conf['ftp_to1']["password"]},端口:{$g_ftp_conf['ftp_to1']["port"]}", "id" => $this->vod_id);
//                        return false;
//                }
//                if (!$ftp_to2->connect()) {
//                        $this->re_code = array("ret" => 3, "reason" => "上传ftp连接失败,地址:{$g_ftp_conf['ftp_to2']["address"]},用户名:{$g_ftp_conf['ftp_to2']["user"]},密码:{$g_ftp_conf['ftp_to2']["password"]},端口:{$g_ftp_conf['ftp_to2']["port"]}", "id" => $this->vod_id);
//                        return false;
//                }
//检查加载文件保存路径是否存在，不存在创建
/**by xs
                if (!is_dir($g_ftp_conf["down_img_dir"])) {
                        $flg = mkdir($g_ftp_conf["down_img_dir"], 0777, true); //递归创建
                        if (!$flg) {
                                $this->re_code = array("ret" => 3, "reason" => "本地创建路径失败:{$g_ftp_conf["down_img_dir"]}", "id" => $this->vod_id);
                                return false;
                        }
                } else {
//如果存在修改权限
                        @chmod($g_ftp_conf["down_img_dir"], 0777);
                }
                end xs**/
//下载文件
                $down_img = str_replace("/prev/KsImg/", "", $img_from);
                //$flg_img = $down_img;
//这个配置项在子配置文件里面
                if (!isset($g_ftp_conf["domain"]) || empty($g_ftp_conf["domain"]))
                                                return true;
                $down_img = $g_ftp_conf["domain"] . $down_img;
//		@$contents=file_get_contents($down_img);
                
                
                
                $cu = new curl();
                $contents = $cu->get($down_img);
                $getinfo = $cu->getInfo();
				//print_r($getinfo);die;
                $infocode = $getinfo['after']['http_code'];
                if ($contents === false || $infocode != '200') {
                	//print_r($infocode);die;
                        $error = $cu->error();
                        $error_no = $cu->errno();
                        $this->re_code = array("ret" => 3, "reason" => "curl获取图片失败失败代码：" . $error_no . ",信息：" . $error . "，图片参数为:{$down_img}", "id" => $this->vod_id);
                        return false;
                }

				//print_r($getinfo);die;
                //将注入图片路径前，加上本地图片路径保存
                //$img_name = np_guid_rand() . strrchr($img_from, '.');
                $img_save_name = str_replace('.JPG','.jpg',$img_from);
                $img_dir = $g_ftp_conf["down_img_dir"] . '/' . $img_save_name; //配置在子配置文件里面
                $path_parts = pathinfo($img_dir);
                 if (!is_dir($path_parts['dirname'])){
                 	echo $path_parts['dirname'];
                     mkdir($path_parts['dirname'], 0777, true);
                 }
                
                $handle = fopen($img_dir, "wb");
                $re = fwrite($handle, $contents);
                fclose($handle);
                if (empty($re)) {
                        $this->re_code = array("ret" => 3, "reason" => "本地保存文件失败", "id" => $this->vod_id);
                        return false;
                }
                //检查本地是否存在该图片
                if(!file_exists($img_dir)){
					$this->re_code = array("ret" => 3, "reason" => "本地保存文件失败","id" => $this->vod_id);
                    return false;						
					//$contents = file_get_contents($down_img);
					//file_put_contents($img_dir,$contents);
                }
				
				
				
				
				
				
				
                /**by xs   
                $img_from = str_replace("/prev/KsImg/", "", $img_from);
                
             
                for ($i=1;$i<=32;$i++){
                	$ftp_result=$this->__import_up_ftp_img($i,$img_from,$img_dir);
                	if ($ftp_result===NULL){
                		continue;
                	}
                	if ($ftp_result===FALSE){
                		return FALSE;
                	}
                }
               xs end */
                
//检查上传文件路径
//                $to_img1 = $g_ftp_conf["ftp_to1"]["address"] . '/' . $img_from;
//                $to_img2 = $g_ftp_conf["ftp_to2"]["address"] . '/' . $img_from;
////上传文件
//                $up_img1 = $ftp_to1->up("/intertv/prev/KsImg/", $img_from, $img_dir);
//                if (!$up_img1) {
//                        $this->re_code = array("ret" => 3, "reason" => "上传文件失败,ftp路径为:" . $g_ftp_conf["ftp_to1"]["address"] . "/prev/KsImg/" . $img_from . ",本地路径为:{$img_dir}", "id" => $this->vod_id);
//                        return false;
//                }
//                $up_img2 = $ftp_to2->up("/intertv/prev/KsImg/", $img_from, $img_dir);
//                if (!$up_img2) {
//                        $this->re_code = array("ret" => 3, "reason" => "上传文件失败,ftp路径为:" . $g_ftp_conf["ftp_to2"]["address"] . "/prev/KsImg/" . $img_from . ",本地路径为:{$img_dir}", "id" => $this->vod_id);
//                        return false;
//                }
//删除本地文件
//unlink($img_dir);
                return true;
        }
        
        
        private  function __import_up_ftp_img($num,$img_from,$img_dir){
        	global $g_ftp_conf;
        	$ftp_key='ftp_to'.$num;
        	//实例化np_ftp类
                $ftp_to1 = new nns_ftp($g_ftp_conf[$ftp_key]["address"], $g_ftp_conf[$ftp_key]["user"], $g_ftp_conf[$ftp_key]["password"], $g_ftp_conf[$ftp_key]["port"]);
              
                if (!$ftp_to1->connect()) {
                        $this->re_code = array("ret" => 3, "reason" => "上传ftp连接失败,地址:{$g_ftp_conf[$ftp_key]["address"]},用户名:{$g_ftp_conf[$ftp_key]["user"]},密码:{$g_ftp_conf[$ftp_key]["password"]},端口:{$g_ftp_conf[$ftp_key]["port"]}", "id" => $this->vod_id);
                        return false;
                }
                
                //检查上传文件路径
                $to_img1 = $g_ftp_conf[$ftp_key]["address"] . '/' . $img_from;
               
//上传文件
                $up_img1 = $ftp_to1->up("/intertv/prev/KsImg/", $img_from, $img_dir);
                if (!$up_img1) {
                        $this->re_code = array("ret" => 3, "reason" => "上传文件失败,ftp路径为:" . $g_ftp_conf["ftp_to1"]["address"] . "/prev/KsImg/" . $img_from . ",本地路径为:{$img_dir}", "id" => $this->vod_id);
                        return false;
                }
                $up_img2 = $ftp_to2->up("/intertv/prev/KsImg/", $img_from, $img_dir);
                if (!$up_img2) {
                        $this->re_code = array("ret" => 3, "reason" => "上传文件失败,ftp路径为:" . $g_ftp_conf["ftp_to2"]["address"] . "/prev/KsImg/" . $img_from . ",本地路径为:{$img_dir}", "id" => $this->vod_id);
                        return false;
                }
                
                return true;
        }

        /**
         * 日志记录函数
         * @param array $params//日志参数组
         * @param string $msg//日志记录说明信息
         * @return null
         */
        static function write_logs($params = array(), $msg = "") {
        	if(!is_dir(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/data/log/mgtv/assets_import/')) {
        		mkdir(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/data/log/mgtv/assets_import/',0777,true);
        	}
                $handle = fopen(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/data/log/mgtv/assets_import/'.date('Y-m-d').'.txt', "a");
                fwrite($handle, "################################" . date("H:i:s", time()));
                
                fwrite($handle, var_export($msg, true) . "\r\n");
                fwrite($handle, var_export($params, true) . "\r\n");
                fclose($handle);
        }

        public function error_logs($params = array(), $msg = "") {
        	self::write_logs($params,$msg);
/*                $handle = fopen(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/data/log/mgtv/assets_import/'.date('Y-m-d').'.txt', "a");
                fwrite($handle, var_export($msg, true) . "\r\n");
                fwrite($handle, var_export($params, true) . "\r\n");
                fclose($handle);*/
        }

        /**
         * 需要改写影片信息 BY S67 2013-04-30
         * 1. MGTV的影片长度保存在分片信息中,需要重写。
         * 2. MGTV的影片上映时间？？？？
         * @param string $video_id:影片id
         * @param array $params {
          "view_len":时长，秒
          }
         */
        private function modify_vod_other_data($video_id, $params = array()) {
                if (empty($params) || empty($video_id)) {
                        return null;
                }
                $set = "";
                foreach ($params as $key => $v) {
                        $set.="nns_{$key}='{$v}',";
                }
                $set = trim($set, ',');
                $sql = "update nns_vod set {$set} where nns_id='{$video_id}' OR nns_asset_import_id='{$video_id}'";
                return nl_execute_by_db($sql, $this->dc->db());
        }

}

//include_once '/data/web/np/np_ftp.php';
//$ftp_to1=new  nns_ftp("58.83.191.23","intertv","hntv*UHB",21);
//$a=$ftp_to1->connect();
//$up_img1=$ftp_to1->up("/intertv/prev/KsImg/","CCCcc.jpg","/data/web/nn_cms/data/a.jpg");
//var_dump($up_img1);die();
//import_assets_class::write_logs(array(1,2,3,4),'fda');